package com.erp.stock.service.impl;

import com.erp.common.util.ServiceUtil;
import com.erp.common.util.StringUtil;
import com.erp.produce.dao.SupplierDao;
import com.erp.stock.dao.RawMaterialDao;
import com.erp.stock.entity.RawMaterial;
import com.erp.stock.mapper.RawMeterialMapper;
import com.erp.stock.service.RawMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class RawMaterialServiceImpl implements RawMaterialService {

    @Autowired
    RawMaterialDao rawMaterialDao;

    @Autowired
    SupplierDao supplierDao;

    @Override
    public Boolean update(RawMaterial rawMaterial) {
        RawMaterial rawMaterial1 = rawMaterialDao.findById(rawMaterial.getId()).get();
        rawMaterial1.setType(rawMaterial.getType());
        rawMaterial1.setName(rawMaterial.getName());
        rawMaterial1.setSupplierId(rawMaterial.getSupplierId());

        return rawMaterialDao.saveAndFlush(rawMaterial1) != null;
    }

    @Override
    public Boolean add(RawMaterial rawMaterial) {
        return rawMaterialDao.save(rawMaterial) != null;
    }

    @Override
    public Boolean deleteIds(Long[] ids) {
        return ServiceUtil.deleteIds(ids,rawMaterialDao);
    }

    @Override
    public List<RawMaterial> listPage(int page, int size) {
        List<RawMaterial> content = rawMaterialDao.findAll(PageRequest.of(page, size)).getContent();
        content.forEach((rawMaterial -> {
            rawMaterial.setSupplierName(supplierDao.findById(rawMaterial.getSupplierId()).get().getSupplierName());
        }));
        return content;
    }

    @Override
    public List<RawMaterial> listPageLike(int page, int size, String column) {
        List<RawMaterial> content = rawMaterialDao.findAllByNameLike(StringUtil.addLike(column), PageRequest.of(page, size));
        content.forEach((rawMaterial -> {
            rawMaterial.setSupplierName(supplierDao.findById(rawMaterial.getSupplierId()).get().getSupplierName());
        }));
        return content;
    }

    @Override
    public List<RawMaterial> findAll() {
        return rawMaterialDao.findAll(new Sort(Sort.Direction.ASC,"id"));
    }
}
